<template>
    <div class="sales-invoice-list">
        <el-card shadow="never">
            <template #header>
                <div class="card-header">
                    <span>销项发票列表</span>
                    <el-button type="primary" @click="goToAdd">添加</el-button>
                </div>
            </template>

            <!-- 条件查询区域 -->
            <el-form :model="queryForm" label-width="100px" size="small" class="query-form" label-position="left">
                <el-row :gutter="16">
                    <el-col :span="8">
                        <el-form-item label="关键字">
                            <el-input v-model="queryForm.keyword" placeholder="用于模糊查询备注等字段" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="发票状态">
                            <el-select v-model="queryForm.invoiceStatus" placeholder="请选择" style="width: 100%">
                                <el-option label="请选择" :value="-1" />
                                <el-option label="待开具" value="0" />
                                <el-option label="已开具" value="1" />
                                <el-option label="已作废" value="2" />
                                <el-option label="已红冲" value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="订单">
                            <el-select v-model="queryForm.orderId" placeholder="请选择" style="width: 100%" filterable>
                                <el-option label="请选择" :value="-1" />
                                <el-option v-for="item in orderList" :key="item.id" :label="item.orderNo"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="16">
                    <el-col :span="6">
                        <el-form-item label="客户">
                            <el-select v-model="queryForm.customerId" placeholder="请选择" style="width: 100%" filterable>
                                <el-option label="请选择" :value="-1" />
                                <el-option v-for="item in customerList" :key="item.customerID"
                                    :label="item.customername" :value="item.customerID" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="开始日期">
                            <el-date-picker v-model="queryForm.startDate" type="date" placeholder="选择开始日期"
                                style="width: 200px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="结束日期">
                            <el-date-picker v-model="queryForm.endDate" type="date" placeholder="选择结束日期"
                                style="width: 200px" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24" style="text-align: right">
                        <el-button type="primary" @click="loadData">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 数据列表 -->
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column prop="invoiceNo" label="发票编号" min-width="180" />
                <el-table-column prop="customerName" label="客户名称" min-width="150" />
                <el-table-column prop="invoiceAmount" label="发票金额" width="120" align="right" :formatter="formatMoney" />
                <el-table-column prop="invoiceDate" label="发票日期" width="160" :formatter="formatDate" />
                <el-table-column prop="invoiceStatusName" label="发票状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.invoiceStatus)">{{ row.invoiceStatusName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" min-width="180" />
                <el-table-column prop="createName" label="创建人" width="100" />
                <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDateTime" />
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="goToEdit(row.invoiceId)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row.invoiceId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs } from '@/Http/http'
import { useCounterStore } from '@/stores/counter'
import type { InvoiceItem, InvoiceQueryParams, DeleteInvoiceParams } from '@/types/salesInvoice'

// 定义分页信息类型
interface Pagination {
    currentPage: number
    pageSize: number
    total: number
}

// 初始化组件
const router = useRouter()
const store = useCounterStore()
const loading = ref(false)
const tableData = ref<InvoiceItem[]>([])
const orderList = ref<any[]>([])
const customerList = ref<any[]>([])

// 初始化查询参数（不含分页参数）
const queryForm = reactive({
    keyword: '',
    invoiceStatus: -1,
    customerId: -1,
    orderId: -1,
    startDate: '',
    endDate: ''
})

// 初始化分页信息
const pagination = reactive<Pagination>({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

/**
 * 加载订单列表数据
 */
const loadOrderList = async () => {
    try {
        const res = await APIs.get('/api/SalesInvoice/DingdanQuery')
        if (res && res.status === 200 && res.data && res.data.code === 100) {
            orderList.value = res.data.data || []
        } else {
            ElMessage.error(res?.data?.msg || '获取订单列表失败')
        }
    } catch (error: any) {
        ElMessage.error(error?.response?.data?.message || '请求失败')
    }
}

/**
 * 加载客户列表数据
 */
const loadCustomerList = async () => {
    try {
        const res = await APIs.get('/api/SalesInvoice/clietQuery')
        if (res && res.status === 200 && res.data && res.data.code === 100) {
            customerList.value = res.data.data || []
        } else {
            ElMessage.error(res?.data?.msg || '获取客户列表失败')
        }
    } catch (error: any) {
        ElMessage.error(error?.response?.data?.message || '请求失败')
    }
}

/**
 * 加载发票列表数据
 */
const loadData = async () => {
    try {
        loading.value = true

        // 构建请求参数，使用pagination中的分页参数
        const params = {
            PageIndex: pagination.currentPage,
            PageSize: pagination.pageSize,
            Keyword: queryForm.keyword || undefined,
            InvoiceStatus: queryForm.invoiceStatus !== -1 ? queryForm.invoiceStatus : undefined,
            CustomerId: queryForm.customerId !== -1 ? queryForm.customerId : undefined,
            OrderId: queryForm.orderId !== -1 ? queryForm.orderId : undefined,
            StartDate: queryForm.startDate || undefined,
            EndDate: queryForm.endDate || undefined
        }

        // 调用API获取数据
        const res = await APIs.get('/api/SalesInvoice/GetSalesInvoiceList', { params })

        // 处理响应数据
        if (res && res.status === 200 && res.data && res.data.code === 100) {
            const responseData = res.data.data || { data: [], total: 0, totalCount: 0 }
            tableData.value = responseData.data || []
            pagination.total = responseData.totalCount || responseData.total || 0
        } else {
            ElMessage.error(res?.data?.msg || '获取发票列表失败')
        }
    } catch (error: any) {
        ElMessage.error(error?.response?.data?.message || '请求失败')
    } finally {
        loading.value = false
    }
}

/**
 * 重置查询条件
 */
const resetQuery = () => {
    queryForm.keyword = ''
    queryForm.invoiceStatus = -1
    queryForm.customerId = -1
    queryForm.orderId = -1
    queryForm.startDate = ''
    queryForm.endDate = ''
    // 重置分页参数
    pagination.currentPage = 1
}

/**
 * 跳转到添加页面
 */
const goToAdd = () => {
    router.push('/SalesInvoice/Add')
}

/**
 * 跳转到编辑页面
 * @param invoiceId 发票ID
 */
const goToEdit = (invoiceId: number) => {
    router.push(`/SalesInvoice/Edit/${invoiceId}`)
}

/**
 * 删除发票
 * @param invoiceId 发票ID
 */
const handleDelete = async (invoiceId: number) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该发票吗？删除后无法恢复。',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        // 构建删除请求参数
        const payload: DeleteInvoiceParams = {
            invoiceId: invoiceId,
            deleteName: store.Users.userNickname || ''
        }

        // 调用删除API
        const res = await APIs.post('/api/SalesInvoice/DeleteSalesInvoice/Delete', payload)

        if (res && res.status === 200) {
            ElMessage.success('删除成功')
            // 重新加载数据
            loadData()
        } else {
            ElMessage.error('删除失败')
        }
    } catch (error) {
        // 用户取消删除操作也会进入catch，但不需要显示错误提示
        if (!(error as any).message?.includes('cancel')) {
            ElMessage.error('删除操作失败')
        }
    }
}

/**
 * 分页大小变化处理
 * @param size 新的页面大小
 */
const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    loadData()
}

/**
 * 当前页码变化处理
 * @param current 新的页码
 */
const handleCurrentChange = (current: number) => {
    pagination.currentPage = current
    loadData()
}

/**
 * 根据发票状态获取标签类型
 * @param status 发票状态
 * @returns 标签类型
 */
const getStatusTagType = (status: number): string => {
    switch (status) {
        case 0: return 'primary'
        case 1: return 'success'
        case 2: return 'danger'
        case 3: return 'warning'
        default: return 'info'
    }
}

/**
 * 格式化金额
 * @param row 数据行
 * @param column 列信息
 * @param cellValue 单元格值
 * @returns 格式化后的金额字符串
 */
const formatMoney = (row: any, column: any, cellValue: any) => {
    const n = Number(cellValue || 0)
    return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

/**
 * 格式化日期
 * @param row 数据行
 * @param column 列信息
 * @param cellValue 单元格值
 * @returns 格式化后的日期字符串
 */
const formatDate = (row: any, column: any, cellValue: any) => {
    if (!cellValue) return ''
    const date = new Date(cellValue)
    return date.toLocaleDateString('zh-CN')
}

/**
 * 格式化日期时间
 * @param row 数据行
 * @param column 列信息
 * @param cellValue 单元格值
 * @returns 格式化后的日期时间字符串
 */
const formatDateTime = (row: any, column: any, cellValue: any) => {
    if (!cellValue) return ''
    const date = new Date(cellValue)
    return date.toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(async () => {
    await loadOrderList()
    await loadCustomerList()
    loadData()
})
</script>

<style scoped>
.sales-invoice-list {
    padding: 12px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.query-form {
    margin-bottom: 16px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 6px;
}

/* 确保查询条件对齐的样式 */
.query-form .el-form-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}

/* 确保表单项标签和输入框对齐 */
.query-form .el-form-item__label {
    text-align: right;
    padding-right: 12px;
    width: 100px;
}

/* 确保输入组件的宽度一致 */
.query-form .el-input,
.query-form .el-select,
.query-form .el-date-picker {
    width: 100%;
}

/* 按钮区域样式优化 */
.query-form .el-row:last-child {
    margin-top: 8px;
}

.pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

/* 优化表格行高和单元格内边距 */
:deep(.el-table) {
    font-size: 14px;
}

:deep(.el-table td),
:deep(.el-table th) {
    padding: 10px 12px;
}
</style>